package com.zhuiyun.project.api.userrecord.service.impl;

import com.zhuiyun.project.api.caseImage.entity.CaseImage;
import com.zhuiyun.project.api.coachmanagement.entity.CoachManagement;
import com.zhuiyun.project.api.memberUserManagement.entity.MemberUserManagement;
import com.zhuiyun.project.api.memberUserManagement.mapper.MemberUserManagementMapper;
import com.zhuiyun.project.api.plan.fitnessPlan.model.FitnessPlanModel;
import com.zhuiyun.project.api.reservation.entity.Reservation;
import com.zhuiyun.project.api.teacherReservation.mapper.TeacherReservationMapper;
import com.zhuiyun.project.api.trainingRecord.entity.TrainingRecord;
import com.zhuiyun.project.api.trainingRecord.mapper.TrainingRecordMapper;
import com.zhuiyun.project.api.trainingRecord.model.CalculateExpend;
import com.zhuiyun.project.api.userrecord.entity.StudentCaseRecords;
import com.zhuiyun.project.api.userrecord.entity.UserRecord;
import com.zhuiyun.project.api.userrecord.mapper.UserRecordMapper;
import com.zhuiyun.project.api.userrecord.model.*;
import com.zhuiyun.project.api.userrecord.service.UserRecordService;
import com.zhuiyun.project.api.weightchangetable.mapper.WeightChangeTableMapper;
import com.zhuiyun.project.api.weightchangetable.model.WeightChangeTableModel;
import com.zhuiyun.project.common.errorCode.CommonException;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.BeanUtils;
import com.zhuiyun.project.utils.UploadFileUtils;
import com.zhuiyun.project.utils.bodyFatPercentageUtils;
import com.zhuiyun.project.utils.uuid.IdUtils;
import com.zhuiyun.project.utils.validator.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName UserRecordServiceImpl
 * @Description TODO
 * @Author wuwan
 * @Date 2023/11/20 14:52
 **/
@Service
public class UserRecordServiceImpl implements UserRecordService {
    @Autowired
    UserRecordMapper userRecordMapper;
    @Autowired
    TrainingRecordMapper trainingRecordMapper;

    @Autowired
    TeacherReservationMapper teacherReservationMapper;

    @Autowired
    WeightChangeTableMapper weightChangeTableMapper;

    @Autowired
    private MemberUserManagementMapper memberUserManagementMapper;

    /*
     * @Author wuwan
     * @Description 上传学员课程记录
     * @Date 2023/11/20 15:08
     * @Return
     */
    @Override
    public CommonResult uploadUserRecord(UploadUserRecordModel uploadUserRecordModel) throws CommonException {
        // 验证参数
        if (ValidatorUtil.ValidationObject(uploadUserRecordModel)){
            // 创建实体对象 用于记录表添加使用
            UserRecord userRecord = new UserRecord();
            // uploadUserRecordModel 对象拷贝到 userRecord
            BeanUtils.copy(uploadUserRecordModel, userRecord);
            // 查询出用户的身高体重年龄性别 用于计算体脂率
            BodyFatModel bodyFatModel = userRecordMapper.selectBodyFat(uploadUserRecordModel.getMemberUserId());
            // 查询出是否拥有改用户
            UserRecord userRecord1 = userRecordMapper.selectByUser(uploadUserRecordModel.getMemberUserId(),uploadUserRecordModel.getRecordId());
            // 判断是否记录过此用户
            if (userRecord1 != null){
                // 创建实体类对象
                UpdateUserRecordModel updateUserRecordModel = new UpdateUserRecordModel();
                // 记录表数据主键id
                Integer recordId = userRecord1.getId();
                // 获取新上传的图片
                String userRecordImg = uploadUserRecordModel.getUserRecordImg();
                // 进行图片拼接
                String s = userRecord1.getUserRecordImg()+","+userRecordImg;
                // 将拼接后的图片存入到实体对象中
                updateUserRecordModel.setUserRecordImg(s);
                // 将体重存储到实体对象中
                updateUserRecordModel.setUserWeight(uploadUserRecordModel.getUserWeight());
                // 将id存储到实体对象中
                updateUserRecordModel.setId(recordId);
                // 计算现体脂率
                Double aDouble = bodyFatPercentageUtils.bodyFatPercentageCalculation(uploadUserRecordModel.getUserWeight(), bodyFatModel.getMemberUserHeight(), bodyFatModel.getMemberUserAge(), bodyFatModel.getMemberUserSex());
                // 将计算出的体脂率存入到实体对象
                updateUserRecordModel.setUserBfp(aDouble);
//                // 拿到现体重
//                Double s1 = userRecord1.getUserWeight();
//                updateUserRecordModel.setChronicleWeight(String.valueOf(s1));

                Integer integer = userRecordMapper.updateUserRecord(updateUserRecordModel);
                if (integer >= 1) {
                    WeightChangeTableModel weightChangeTableModel =new WeightChangeTableModel();
                    weightChangeTableModel.setMemberUserId(uploadUserRecordModel.getMemberUserId());
                    weightChangeTableModel.setChronicleWeight(uploadUserRecordModel.getUserWeight());
                    weightChangeTableModel.setLastWeight(userRecord1.getUserWeight());
                    weightChangeTableMapper.addWeightChangeTable(weightChangeTableModel);
                    CountExpend(uploadUserRecordModel,aDouble);
                    return CommonResult.ok(CommonResult.ok(EmErrorCode.UPDATE_OK));
                }
                return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
            }

            // 对图片添加
            userRecord.setUserRecordImg(uploadUserRecordModel.getUserRecordImg());
            // 计算学员体脂率
            Double aDouble = bodyFatPercentageUtils.bodyFatPercentageCalculation(uploadUserRecordModel.getUserWeight(), bodyFatModel.getMemberUserHeight(), bodyFatModel.getMemberUserAge(), bodyFatModel.getMemberUserSex());
            userRecord.setUserBfp(aDouble);
//            String s = Double.toString(uploadUserRecordModel.getUserWeight());
//            userRecord.setChronicleWeight(s);
            // 执行添加
            Integer integer = userRecordMapper.uploadUserRecord(userRecord);
            if (integer >= 1) {
                WeightChangeTableModel weightChangeTableModel =new WeightChangeTableModel();
                weightChangeTableModel.setMemberUserId(uploadUserRecordModel.getMemberUserId());
                weightChangeTableModel.setChronicleWeight(uploadUserRecordModel.getUserWeight());
                weightChangeTableModel.setLastWeight(uploadUserRecordModel.getUserWeight());
                weightChangeTableMapper.addWeightChangeTable(weightChangeTableModel);
                CountExpend(uploadUserRecordModel,aDouble);
                return CommonResult.ok(CommonResult.ok(EmErrorCode.SAVE_OK));
            }
            return CommonResult.ok(EmErrorCode.SAVE_ERROR);
        }else {
            return CommonResult.ok(EmErrorCode.SAVE_ERROR);
        }
    }
    /*
    * @Author wuwan
    * @Description 统计表添加 用于上放方法调用
    * @Date 2023/11/24 14:46
    * @Return
    */
    public void CountExpend(UploadUserRecordModel uploadUserRecordModel,Double aDouble){
        // 获取uploadUserRecordModel中的用户id
        Integer userId = uploadUserRecordModel.getMemberUserId();
        // 创建实体对象  用于统计表添加使用
        TrainingRecord trainingRecord = new TrainingRecord();
        // 存入用户id
        trainingRecord.setUserId(uploadUserRecordModel.getMemberUserId());
        // 存入用户锻炼完后的体重
        trainingRecord.setUserWeight(uploadUserRecordModel.getUserWeight());
        // 存入用户锻炼完后的体脂率
        trainingRecord.setUserBfp(aDouble);
        // 查询出计划id
        FitnessPlanModel fitnessPlanModel = teacherReservationMapper.selectUserPlan(userId);
        // 根据计划id查询出所有动作的能量消耗
        CalculateExpend calculateExpends = trainingRecordMapper.selectExpend(fitnessPlanModel.getId());
        Integer totalExpend = calculateExpends.getTotalExpend();
        trainingRecord.setEnergyConsumption(Double.valueOf(totalExpend));
        trainingRecordMapper.saveTrainingRecord(trainingRecord);
    }
    /*
     * @Author wuwan
     * @Description 添加图片记录信息
     * @Date 2023/11/21 15:32
     * @Return
     */
    @Override
    @Transactional
    public String  uploadImg(MultipartFile file) {
        String s = UploadFileUtils.uploadFile(file);
        return s;
    }
    /*
     * @Author wuwan
     * @Description 教练查询全部用户记录
     * @Date 2023/11/21 15:32
     * @Return
     */
    @Override
    public CommonResult selectUserInformation(Integer recordId) {
        Integer coachId = recordId;
        return CommonResult.ok(selectTeacherCase(coachId));
    }
    /*
    * @Author wuwan
    * @Description 将用户记录提交到案例表
    * @Date 2023/11/23 11:05
    * @Return
    */
    @Override
    public CommonResult addCaseRecords(AddCaseRecordsModel addCaseRecordsModel) {
        CoachManagement byCoachVenueId = userRecordMapper.getByCoachVenueId(addCaseRecordsModel.getCoachId());
        addCaseRecordsModel.setVenueUniqueIdentifier(byCoachVenueId.getVenueUniqueIdentifier());
        Integer integer = userRecordMapper.addCaseRecords(addCaseRecordsModel);
        if (integer == 1){
            return CommonResult.ok("提交成功");
        }
        return CommonResult.error("提交失败");
    }
    /*
     * @Author wuwan
     * @Description 上传案例开始时图片
     * @Date 2023/11/20 15:08
     * @Return
     */
    @Override
    @Transactional
    public String uploadStartPhoto(MultipartFile file) {
        String s = UploadFileUtils.uploadFile(file);
        return s;
    }
    /*
     * @Author wuwan
     * @Description 上传案例结束时图片
     * @Date 2023/11/20 15:08
     * @Return
     */
    @Override
    @Transactional
    public String uploadEndingPhoto(MultipartFile files) {
        String ss = UploadFileUtils.uploadFile(files);
        return ss;
    }
    /*
    * @Author wuwan
    * @Description 查询所有案例 对数据进行处理
    * @Date 2023/11/24 14:46
    * @Return
    */
    @Override
    public CommonResult selectUserCase(Integer tid, Integer caseStatus) {
        List<StudentCaseRecordsModel> studentCaseRecords = userRecordMapper.selectUserCase(tid,caseStatus);
        for (int i = 0; i < studentCaseRecords.size(); i++) {
            // 创建实体
            StudentCaseRecordsModel studentCaseRecords1 = studentCaseRecords.get(i);
            // 查询出用户的最新记录时间
            UserRecord userRecord = userRecordMapper.selectUserTrainingTime(studentCaseRecords1.getMemberId());
            // 获取时间
            Date createTime = userRecord.getCreateTime();
            // 当前时间
            Date currentDate = new Date();
            // 当前时间减去 最开始时间 转换为long类型
            long differenceInMillis = currentDate.getTime() - createTime.getTime();
            // 转换为天数 如10(天)
            long differenceInDays = differenceInMillis / (24 * 60 * 60 * 1000);
            String differenceInDaysString = String.valueOf(differenceInDays);
            studentCaseRecords1.setByTime(differenceInDaysString);
            // 计算出变化的体脂率 体重的变化  如 对比之前瘦了多少 体脂率减了多少
            SelectUserInformationModel selectUserInformationModel = userRecordMapper.selectUserInformationById(studentCaseRecords1.getMemberId(), tid);
            // 计算体重
            Double reduceWeight = selectUserInformationModel.getMemberUserWeight() - selectUserInformationModel.getUserWeight();
            // 计算体脂
            Double reduceBfp = selectUserInformationModel.getMemberUserBodyFat() - selectUserInformationModel.getUserBfp();
            double roundedValue = Math.round(reduceBfp * 100.0) / 100.0;
            // 存入实体对象中返回
            studentCaseRecords1.setReduceWeight(reduceWeight);
            studentCaseRecords1.setReduceBfp(roundedValue);
            MemberUserManagement byUserName = userRecordMapper.getByUserName(studentCaseRecords1.getMemberId());
            studentCaseRecords1.setUserName(byUserName.getMemberUserRealName());
        }
        return CommonResult.ok(studentCaseRecords);
    }


    /**
     * @Author wx
     * @Description 根据学员编号 教练编号查询案例
     * @Date 2023/12/4 13:53
     * @Return
     * @param coachId,memberId
     */
    @Override
    public CommonResult selectTeacherCase(Integer coachId) {
        List<Map<String, Object>> result = new ArrayList<>();
        // 查询训练数据
        List<UserRecord> studentCaseRecordsList = userRecordMapper.selectTeacherCase(coachId);
        for (UserRecord record : studentCaseRecordsList) {
            Integer memberId = record.getMemberUserId();
            Integer coachIdInRecord = record.getRecordId();
            Double userWeight = record.getUserWeight();
            Double userBfp = record.getUserBfp();
            String fraction =record.getFraction();
            Date createTime = record.getCreateTime();
            Integer numberSize = record.getNumberSize();
            // 查询用户数据
            MemberUserManagement memberUserManagement = memberUserManagementMapper.selectByMemberId(memberId);
            String memberUserName = memberUserManagement.getMemberUserRealName();
            Integer userId = memberUserManagement.getId();
            Date createTimes = memberUserManagement.getCreateTime();
            Integer memberUserPhoto = memberUserManagement.getMemberUserPhoto();
            // 查询该学员案例图片
            List<CaseImage> caseImages = userRecordMapper.selectCasePhoto(memberId,coachIdInRecord);
            List<String> caseEndingPhotoList = new ArrayList<>();
            for (CaseImage caseImage : caseImages) {
                caseEndingPhotoList.add(caseImage.getActionImage());
            }
            Map<String, Object> data = new HashMap<>();
            data.put("memberUserName", memberUserName);
            data.put("caseCount", caseEndingPhotoList.size());
            data.put("caseEndingPhotoList", caseEndingPhotoList);
            data.put("memberUserId",userId);
            data.put("userWeight",userWeight);
            data.put("userBfp",userBfp);
            data.put("fraction",fraction);
            data.put("createTime",createTime);
            data.put("numberSize",numberSize);
            data.put("createTimes",createTimes);
            data.put("memberUserPhoto",memberUserPhoto);
            result.add(data);
        }
        return CommonResult.ok(result);
    }

    /**
     * @Author wx
     * @Description 修改案例评分
     * @Date 2023/12/12 14:48
     * @Return
     * @param fraction
     */
    @Override
    public CommonResult updateCsaeFroction(String fraction, Integer coachId, Integer memberUserId) {
        return CommonResult.ok(userRecordMapper.updateCsaeFroctionById(fraction,coachId,memberUserId));
    }

}
